package cn.com.callback

import java.nio.charset.Charset
import java.security.MessageDigest
import java.security.NoSuchAlgorithmException
import java.text.SimpleDateFormat
import com.alibaba.fastjson.JSONObject
import org.apache.commons.logging.Log

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.github.qcloudsms.httpclient.HTTPException;
import com.wisdge.utils.security.MD5

import groovy.json.*;

import cn.com.elite.EliteBean;
import cn.com.elite.Util;


import java.sql.Date
import org.apache.commons.logging.LogFactory
import org.apache.http.HttpEntity
import org.apache.http.HttpResponse
import org.apache.http.client.methods.HttpPost
import org.apache.http.entity.ContentType
import org.apache.http.entity.mime.HttpMultipartMode
import org.apache.http.entity.mime.MultipartEntityBuilder
import org.apache.http.entity.mime.content.StringBody
import org.apache.http.impl.client.DefaultHttpClient
import org.apache.http.util.EntityUtils;

public class savarecord implements ServiceBackInvoke{
	
	private static final Log log =LogFactory.getLog(savarecord.class);

	public String doCallBack(EliteBean eliteBean,HttpServletRequest request,HttpServletResponse response){

		def enterpriseId = '7500393';
		def token = '5d0eb907c260fd751a54d91dab942f9b';
		def returnDealFlag="0";//响应标识 1 成功，0 失败
		long timestamp =	System.currentTimeMillis() / 1000;		
		def sign = enterpriseId+timestamp+token;
		try {
			MessageDigest md = MessageDigest.getInstance("MD5")
			md.update(sign.getBytes())//update处理
			byte [] encryContext = md.digest()//调用该方法完成计算
	
			int i
			StringBuffer buf = new StringBuffer("")
			for (int offset = 0; offset < encryContext.length; offset++) {//做相应的转化（十六进制）
				i = encryContext[offset]
				if (i < 0) i += 256
				if (i < 16) buf.append("0")
			sign = buf.append(Integer.toHexString(i)).toString()
		   }
		   log.debug("32result: " + buf.toString())// 32位的加密
		   log.debug("16result: " + buf.toString().substring(8, 24))// 16位的加密
		} catch (NoSuchAlgorithmException e) {
			// TODO Auto-generated catch block
			e.printStackTrace()
		}
		//查询ngs文件上传域名，
				def returnsql=eliteBean.chaxun_sql("select PARAMETERVALUE from sysc_parameter sp where sp.PARAMETER_ID='NGSURL'","dataSource");
				def returnstring = returnsql[0];
				def ngsFSUrl=returnstring.get("PARAMETERVALUE");
		String cloudConfigSQL = "select r.RECORD_GUID,r.initcallid,r.CALLTYPE,CONCAT(r.RECORDNO,'.mp3') as filename from record  r where r.indexstatus = 0 AND convert(varchar(10),r.STARTTIME,120) =convert(varchar(10),GETDATE(),120) order by r.STARTTIME  ";
			List<?> cloudConfigList = (List<?>) eliteBean.chaxun_sql(cloudConfigSQL, "dataSource");
			if (cloudConfigList.size() > 0) {
				//设置默认值
				def RECORD_GUID="";
				def recordFile = "1";
				def CALLTYPE ="1";
				def recordType = "ib"
				def filename =""
			for(int m = 0 ; m < cloudConfigList.size();m++){	
				RECORD_GUID = (String)( ((Map<?, ?>) cloudConfigList.get(m)).get("RECORD_GUID"));
				recordFile = (String)((Map<?, ?>) cloudConfigList.get(m)).get("initcallid");
				CALLTYPE = (String) ((Map<?, ?>) cloudConfigList.get(m)).get("CALLTYPE");
				filename = (String) ((Map<?, ?>) cloudConfigList.get(m)).get("filename");
					log.debug("filename:"+filename);
					if(CALLTYPE.equals("1")){
						recordType = "ib";
						}else{
						recordType = "ob";
					}
		
		
		//调取话务详情接口获取录音全地址
		def url  = 'https://api-5.cticloud.cn/interface/v10/cdr/'+recordType+'/query?validateType=2&enterpriseId='+enterpriseId+'&timestamp='+timestamp+'&sign='+sign+'&uniqueId='+recordFile;
		log.debug('url	'+url);
		
			
		def result = interfaceUtil(url, "");
		log.debug(result);
		if(result.equals('1')){
			log.debug('接口调用失败');
		}else {
			log.debug('result:'+result);
			String cloudResponseStr=result.toString();
			//初步解析获取接口返回状态
			JSONObject reponseBodyJsonObject = JSONObject.parseObject(cloudResponseStr);
			String resultCode = reponseBodyJsonObject.getString("result");
			String resultMsg = reponseBodyJsonObject.getString("description");
			log.debug('resultCode:'+resultCode);
			//接口返回成功，则继续解压里面的内容
			if(resultCode.equals('0')) {
			def cloudConfigLists =[];
			cloudConfigLists = reponseBodyJsonObject.getJSONArray("data");
			//log.debug('我开始了！');
			if (cloudConfigLists.size() > 0) {
					//开始解析内容
				for (int a = 0;a<cloudConfigLists.size();a++) {
					//唯一id
					String uniqueId = cloudConfigLists.getJSONObject(a).("uniqueId");
					//解析录音信息
					def recordFilelist =[];
					 recordFilelist = cloudConfigLists.getJSONObject(a).("recordFile");
					 //录音地址
					 String file = recordFilelist.getJSONObject(0).("file");
					 //录音类型
					 String type = recordFilelist.getJSONObject(0).("type");
				
					 def url2  = 'https://api-5.cticloud.cn/interface/v10/record/getUrl?validateType=2&enterpriseId='+enterpriseId+'&timestamp='+timestamp+'&sign='+sign+'&recordType='+type+'&recordFile='+file;
					 def result2 = interfaceUtil(url2, "");
					 log.debug("result2:" + result2)
					 JSONObject result2JsonObject = JSONObject.parseObject(result2);
					 String code = result2JsonObject.getString("result");
					 if ("0".equals(code)) {
						 String dataUrl = result2JsonObject.getString("data");
						 byte[] fileData = downLoadFromUrl(dataUrl);
						 log.debug('filename:'+filename+' ngsFSUrl:'+ngsFSUrl);
						 log.debug(ngsFSUrl + "upload_"+fileData+ filename);
						 String resultString = uploadFileByByte(ngsFSUrl + "upload_", fileData, filename);  //fileName 你看传什么xxx.mp3
						 log.debug("resultString:" + resultString);
						 //例如： {"code":1,"message":"test.jpg","value":"record/test_1598005258263.jpg"}
						 //record/test_1598005258263.jpg： 上传完文件生成的相对路径，需要拼上域名，然后就可以直接访问
						 JSONObject resultBody = JSONObject.parseObject(resultString); 
						 //修改录音表记录，打上已上传标识
						 code = resultBody.getString("code");
						 if("1".equals(code)){
						 eliteBean.update("update record set indexstatus = 5 ,documentpath='"+ngsFSUrl+'get?file='+resultBody.getString("value")+"' where RECORD_GUID ='"+RECORD_GUID+"'","dataSource");
						 }else{
							log.debug('上传失败');
							 
						 }
					 }
					
					returnDealFlag = "1";
				}
			}
			}else {
					returnDealFlag = "0";
					
					log.debug('IB接口返回 失败');
					
				}
			}
			}
			
	}
	return returnDealFlag;
	}
	
	
	
	
	//调用接口，返回接口获取信息
	static Object interfaceUtil(String path,String data) throws Exception   {
	String str=new String();
	str = '222';
	try {
		URL url = new URL(path)
		//打开和url之间的连接
		HttpURLConnection conn = (HttpURLConnection) url.openConnection()
		PrintWriter out = null
		
		/**设置URLConnection的参数和普通的请求属性****start***/
	   
		conn.setRequestProperty("accept", "*/*")
		conn.setRequestProperty("connection", "Keep-Alive")
		conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1)")
		
		/**设置URLConnection的参数和普通的请求属性****end***/
		
		//设置是否向httpUrlConnection输出，设置是否从httpUrlConnection读入，此外发送post请求必须设置这两个
		//最常用的Http请求无非是get和post，get请求可以获取静态页面，也可以把参数放在URL字串后面，传递给servlet，
		//post与get的 不同之处在于post的参数不是放在URL字串里面，而是放在http请求的正文内。
		conn.setDoOutput(true)
		conn.setDoInput(true)
		
		conn.setRequestMethod("GET")//GET和POST必须全大写
		/**GET方法请求*****start*/
		/**
		 * 如果只是发送GET方式请求，使用connet方法建立和远程资源之间的实际连接即可；
		 * 如果发送POST方式的请求，需要获取URLConnection实例对应的输出流来发送请求参数。
		 * */
		conn.connect()
		
		/**GET方法请求*****end*/
		
		/***POST方法请求****start*/
		
		/*out = new PrintWriter(conn.getOutputStream());//获取URLConnection对象对应的输出流
		
		out.print(data);//发送请求参数即数据
		
		out.flush();//缓冲数据
		*/
		/***POST方法请求****end*/
		
		//获取URLConnection对象对应的输入流
		InputStream is = conn.getInputStream()
		//构造一个字符流缓存
		BufferedReader br = new BufferedReader(new InputStreamReader(is))
		
		while ((str = br.readLine()) != null) {
			str=new String(str.getBytes(),"UTF-8")//解决中文乱码问题
			//log.debug(str);
			return str;
		}
		//关闭流
		is.close()
		//断开连接，最好写上，disconnect是在底层tcp socket链接空闲时才切断。如果正在被其他线程使用就不切断。
		//固定多线程的话，如果不disconnect，链接会增多，直到收发不出信息。写上disconnect后正常一些。
		conn.disconnect();
		
		log.debug("完整结束")
	} catch (Exception e) {
		e.printStackTrace()
		return '1';
	}
	
	}
	
	
	public String uploadFileByByte(String url, byte[] fileData, String filename) throws Exception{
		DefaultHttpClient httpClient=new DefaultHttpClient();
		String content="";
		try{
			HttpPost httpPost = new HttpPost(url);
			httpPost.setHeader("Accept-Language","zh-cn,zh;q=0.5");
			httpPost.setHeader("Accept-Charset","GBK,utf-8;q=0.7,*;q=0.7");
			httpPost.setHeader("Connection","keep-alive");
			MultipartEntityBuilder mutiEntity = MultipartEntityBuilder.create();
			mutiEntity.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
			mutiEntity.addPart("euPath",new StringBody("record", Charset.forName("utf-8")));
			mutiEntity.addBinaryBody("euFile", fileData, ContentType.DEFAULT_BINARY, filename);
//			mutiEntity.addPart("euFile",new FileBody(file));
//			mutiEntity.addPart("euName", new StringBody(filename, Charset.forName("utf-8")));
			httpPost.setEntity(mutiEntity.build());
			HttpResponse  httpResponse = httpClient.execute(httpPost);
			HttpEntity httpEntity =  httpResponse.getEntity();
			content = EntityUtils.toString(httpEntity);
		}catch(Exception e){
			log.error("",e);
		}finally{
			if(httpClient!=null){
				httpClient.close();
			}
			return content;
		}
	}

	
	/**
	 * 从网络Url中下载文件
	 * @param urlStr
	 * @param fileName
	 * @param savePath
	 * @throws IOException
	 */
	public byte[] downLoadFromUrl(String urlStr) throws Exception{
		URL url = new URL(urlStr);
		HttpURLConnection conn = (HttpURLConnection)url.openConnection();
				//设置超时间为3秒
		conn.setConnectTimeout(3*1000);
		//防止屏蔽程序抓取而返回403错误
		conn.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)");
 
		//得到输入流
		return readInputStream(conn.getInputStream());
	}

	/**
	 * 从输入流中获取字节数组
	 * @param inputStream
	 * @return
	 * @throws IOException
	 */
	public byte[] readInputStream(InputStream inputStream) throws Exception {
		byte[] buffer = new byte[1024];
		int len = 0;
		ByteArrayOutputStream bos = new ByteArrayOutputStream();
		while((len = inputStream.read(buffer)) != -1) {
			bos.write(buffer, 0, len);
		}
		bos.close();
		if (inputStream != null) {
			inputStream.close();
		}
		return bos.toByteArray();
	}
}